package com.erp.service.entity;

import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.TextUtils;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.DateDeserializer;
/**
 * dotnet日期反序列化方法
 * @author ccl
 *
 */
public class DotnetDateDeserializer extends DateDeserializer {
    public final static DotnetDateDeserializer instance = new DotnetDateDeserializer();

    /**
     * 实现反序列化方法
     * @param parser 默认转换器
     * @param clazz 转换类型
     * @param fieldName 字段名
     */
    @SuppressWarnings("unchecked")
    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
	try {
	    Object val = parser.parse();

	    if (val == null) {
		return null;
	    }
	    String JSONDateToMilliseconds = "\\/(Date\\((.*?)(\\+.*)?\\))\\/";
	    Pattern pattern = Pattern.compile(JSONDateToMilliseconds);
	    Matcher matcher = pattern.matcher(val.toString());
	    String result = null;
	    String timeZoneString = null;
	    while (matcher.find()) {
		result = matcher.group(2);
		timeZoneString = matcher.group(3);
	    }
	    Date resultDate = new Date(new Long(result) - TimeZone.getDefault().getRawOffset());
	    Calendar calendar = Calendar.getInstance();
	    calendar.setTime(resultDate);
	    if (!TextUtils.isEmpty(timeZoneString)) {
		double timeZone = Double.parseDouble(timeZoneString) / 100.0;
		calendar.add(Calendar.HOUR, (int) timeZone);
	    }
	    return (T) calendar.getTime();
	} catch (Exception e) {
	    e.printStackTrace();
	}

	return super.<T>deserialze(parser, clazz, fieldName);
    }

}